from django.contrib.auth.models import AbstractUser
from django.db import models


class Institution(models.Model):
    """机构模型"""
    code = models.CharField(max_length=50, unique=True, verbose_name="机构代码")
    name = models.CharField(max_length=200, verbose_name="机构名称")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        db_table = 'accounts_institution'
        verbose_name = "机构"
        verbose_name_plural = "机构"
        ordering = ['code']  # 添加默认排序

    def __str__(self):
        return f"{self.name} ({self.code})"


class Laboratory(models.Model):
    """实验室模型"""
    institution = models.ForeignKey(Institution, on_delete=models.CASCADE, verbose_name="所属机构")
    code = models.CharField(max_length=100, verbose_name="实验室代码")
    name = models.CharField(max_length=200, verbose_name="实验室名称")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        db_table = 'accounts_laboratory'
        unique_together = [['institution', 'code']]
        verbose_name = "实验室"
        verbose_name_plural = "实验室"
        ordering = ['institution__code', 'code']  # 添加默认排序

    def __str__(self):
        return f"{self.name} - {self.institution.name}"


class CustomUser(AbstractUser):
    """扩展用户模型"""
    
    # 用户类型选择
    USER_TYPE_CHOICES = [
        ('member', '实验室成员'),
        ('laboratory', '实验室管理员'),
    ]
    
    email = models.EmailField(unique=True, verbose_name="邮箱")
    full_name = models.CharField(max_length=100, verbose_name="姓名")
    phone = models.CharField(max_length=20, blank=True, null=True, verbose_name="电话")
    institution = models.ForeignKey(Institution, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="所属机构")
    laboratory = models.ForeignKey(Laboratory, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="所属实验室")
    user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICES, default='member', verbose_name="用户类型")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'full_name']

    class Meta:
        db_table = 'accounts_customuser'
        verbose_name = "用户"
        verbose_name_plural = "用户"
        ordering = ['-created_at']  # 添加默认排序

    def __str__(self):
        return f"{self.full_name} ({self.email})"
        
    def can_login_as_laboratory(self):
        """检查用户是否可以以实验室身份登录"""
        return self.user_type == 'laboratory' or self.is_staff or self.is_superuser